<?php
namespace app\controller;

use think\cache\driver\Redis;
use think\facade\Cache;
use think\facade\Db;
use think\Request;

class SanCloud
{

	/**
	 * 请求QPS限制
	 *
	 * return json
	 */
	private function qps_firewall($name, $number = 600)
	{
		$cacheName = 'qps_' . $name;
		$pass = env('redis.password', '123456');
		$redis = new Redis();
		$redis->auth($pass);
		$exists = $redis->exists($cacheName);
		if($exists) {
			$count = $redis->get($cacheName);
			if($count > $number) {
				return true;
			}
			$redis->incr($cacheName);
		} else {
			$redis->incr($cacheName);
			$redis->expire($cacheName, 300);
		}
		return false;
	}

	/**
	 *  获取用户真实地址
	 *
	 * @return    string  返回用户ip
	 */
	function GetIP()
	{
			static $realip = NULL;
			if ($realip !== NULL)
			{
					return $realip;
			}
			if (isset($_SERVER))
			{
					if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
					{
							$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
							/* 取X-Forwarded-For中第x个非unknown的有效IP字符? */
							foreach ($arr as $ip)
							{
									$ip = trim($ip);
									if ($ip != 'unknown')
									{
											$realip = $ip;
											break;
									}
							}
					}
					elseif (isset($_SERVER['HTTP_CLIENT_IP']))
					{
							$realip = $_SERVER['HTTP_CLIENT_IP'];
					}
					else
					{
							if (isset($_SERVER['REMOTE_ADDR']))
							{
									$realip = $_SERVER['REMOTE_ADDR'];
							}
							else
							{
									$realip = '0.0.0.0';
							}
					}
			}
			else
			{
					if (getenv('HTTP_X_FORWARDED_FOR'))
					{
							$realip = getenv('HTTP_X_FORWARDED_FOR');
					}
					elseif (getenv('HTTP_CLIENT_IP'))
					{
							$realip = getenv('HTTP_CLIENT_IP');
					}
					else
					{
							$realip = getenv('REMOTE_ADDR');
					}
			}
			preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
			$realip = ! empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';
			return $realip;
	}
	
	/**
	 * 查询微信接口
	 * 纠正时间2021-11-11 12-20
	 * 最后纠正时间2022-10-26 11-20
	 * return json
	 */
	public function getData(Request $request)
	{
		$address = $this->GetIP();
		if( $this->qps_firewall('get_'.$address, 100) ) {
			return json(['code'=>8888, 'data'=> []]);
		}

		$t = $request->param('t', '', 'trim');
		$vid = $request->param('vid', '', 'trim');
		$header = $request->header('user-agent');
		$pages = $request->param('pages', '', 'trim');
		$width = $request->param('width', '', 'trim');
		$height = $request->param('height', '', 'trim');
		$language = $request->param('language', '', 'trim');
		$platform = $request->param('platform', '', 'trim');
		$device = $request->param('device', '', 'trim');
		$dev = $request->param('dev', '', 'trim');
		$code = $request->param('code', '', 'trim');
		$href = $request->param('href', '', 'trim');
		$word = $request->param('word', '', 'trim');
		$timer = $request->param('timer', '', 'trim');
		$offset = $request->param('offset', '', 'trim');
		$referrer = $request->param('referrer', '', 'trim');
		$userAgent = $request->param('userAgent', '', 'trim');
		$companyId = $request->param('companyId', '', 'trim');
		$colordepth = $request->param('colordepth', '', 'trim');
		$e_keywordid = $request->param('e_keywordid', '', 'trim');

		if( empty($href) ) {
			return json(['code'=>1000, 'data'=> []]);
		}

		if( empty($header) ) {
			return json(['code'=>1000, 'data'=> []]);
		}

		if( empty($companyId) ) {
			return json(['code'=>1000, 'data'=> []]);
		}

		if($word) {
			$word = urldecode($word);
		} else {
			$word = null;
		}

		// 获取URL域名
		$domainUrl = cloud_domain_format($href);
		if( empty($domainUrl) ) {
			return json(['code'=>1000, 'data'=> []]);
		}

		// URL解码
		if($href) {
			$href = urldecode($href);
		}
		
		if($referrer) {
			$referrer = urldecode($referrer);
		}

		// 拦截蜘蛛访问
		$userAgent = strtolower($userAgent);
		foreach( ['bot', 'crawl', 'spider' ,'slurp', 'sohu-search', 'lycos', 'robozilla'] as $value ) {
			if( strpos($userAgent, $value) !== false ) {
				return json(['code'=>2000, 'data'=> []]);
			}
		}

		// 拦截访问IP
		$interceptPath = app()->getRootPath() . 'data' . DIRECTORY_SEPARATOR . md5($companyId . 'spider' );
		if ( file_exists($interceptPath) ) {
			$interceptData = file_get_contents($interceptPath);
			if( $interceptData ) {
				$getAddress = explode(".", $address);
				if( strpos($interceptData, "{$getAddress[0]}.{$getAddress[1]}.{$getAddress[2]}") !== false ) {
					return json(['code'=>2000, 'data'=> []]);
				}
			}
		}

		// 查询访问记录
		$accesMd5 = md5(date('Ymd') . $companyId . $domainUrl . $userAgent . $address);
		$queryAcces = Db::table('cfg_access')->field('id, service')->where('companyId', $companyId)->where('md5', $accesMd5)->find();
		if( isset($queryAcces['id']) ) {
			$wechatArray = unserialize($queryAcces['service']);
			if( isset($wechatArray['wechat']) ) {
				return json(['code'=>0, 'data'=> [
					'sex'=> $wechatArray['sex'],
					'name'=> $wechatArray['name'],
					'phone'=> $wechatArray['phone'],
					'wechat'=> $wechatArray['wechat'],
					'qrcode' => $wechatArray['qrcode'],
					'company' => $wechatArray['company']
				], 'sign' => $accesMd5]);
			}
		}

		// 查询落地页
		$siteQuery = Db::table('cfg_site')->field('id, bazaar, SiteModel, Copyright')->where('companyId', $companyId)
		  ->where('DomainUrl', $domainUrl)->where('status', 1)->find();
		if( !is_array($siteQuery) ) {
			return json(['code'=> 3000, 'data'=> []]);
		}

		if( !isset($siteQuery['id']) ) {
			return json(['code'=> 3000, 'data'=> []]);
		}

		if( empty($siteQuery['id']) ) {
			return json(['code'=> 3000, 'data'=> []]);
		}

		// 查询市场
		if( empty($siteQuery['SiteModel']) ) {
			$bazaarQuery = Db::table('cfg_bazaar')->field('id, model')->where('id', $siteQuery['bazaar'])->where('status', 1)->find();
			if( !is_array($bazaarQuery) ) {
				return json(['code'=>5000, 'data'=> []]);
			}
			if( !isset($bazaarQuery['id']) ) {
				return json(['code'=>5000, 'data'=> []]);
			}
			if( empty($bazaarQuery['id']) ) {
				return json(['code'=>5000, 'data'=> []]);
			}
			$siteQuery['SiteModel'] = $bazaarQuery['model'];
		}

		// 查询当前推广平台
		$expandQuery = Db::table('cfg_expand')->field('id, userid, customerid, contact, username, userType')->where('bazaarId', $siteQuery['bazaar'])->whereFindInSet('domainIds', $siteQuery['id'])->find();
		if( !is_array($expandQuery) ) {
			return json(['code'=>4000, 'data'=> []]);
		}
		if( !isset($expandQuery['id']) ) {
			return json(['code'=>4000, 'data'=> []]);
		}
		if( empty($expandQuery['id']) ) {
			return json(['code'=>4000, 'data'=> []]);
		}

		// 查询客服展示
		$servicePlanQuery = Db::table('cfg_service_plan')->where('companyId', $companyId)->where('url', $domainUrl)->value('wechat');
		if( empty($servicePlanQuery) ) {
			return json(['code'=>6000, 'data'=> []]);
		}

		// 查询客服列表
		$serviceQuery = Db::table('cfg_service')->where('companyId', $companyId)->field('id, nickname, wechat, phone, qrcode, weight, sex')
		 ->where('id', 'in', $servicePlanQuery)->where('status', 1)->order( $siteQuery['SiteModel'] == 1 ? 'number' : 'lasttime', 'asc')->select()->toArray();
		if( count($serviceQuery) == 0 ) {
			return json(['code'=>7000, 'data'=> []]);
		}

		// 客服展示模式
		$wechatData = [];
		switch ($siteQuery['SiteModel']) {
			case 2: // 随机展示
				$wechatData = $serviceQuery[array_rand($serviceQuery, 1)];
				break;
			case 3: // 权重展示
				$index = 0;
				$weight = 0;
				$count = count($serviceQuery);
				$number = mt_rand(0, array_sum(array_column($serviceQuery, 'weight')));
				while($index < $count) {
					$weight += $serviceQuery[$index]['weight'];
					if($weight >= $number) {
						break;
					}
					$index++;
				}
				$wechatData = $serviceQuery[$index];
				break;
			default: // 轮番展示 OR 均衡展示
				$wechatData = $serviceQuery[0];
		}

        // 正常微信展示
        $wechatArray = ['wechat'=> $wechatData['wechat'], 'sex'=> $wechatData['sex'], 'name'=> $wechatData['nickname'], 'phone'=> $wechatData['phone'], 'qrcode' => $wechatData['qrcode'], 'company' => $siteQuery['Copyright']];

		// 拦截内部计划
		$internal = Db::table('cfg_service_internal')->where('status', 1)->whereFindInSet('domain', $domainUrl)->select()->toArray();
		$numberCount = count($internal);
		if( $numberCount > 0) {
			$index = array_rand($internal, 1);
			$wechatData = $internal[$index];
			$queryHour = intval(date('G'));
			if( $queryHour >= intval($wechatData['startHour']) && $queryHour <= intval($wechatData['endHour']) ) {
				$ipLocation = new \Net\IpLocation( app()->getRootPath() . 'data' . DIRECTORY_SEPARATOR . 'qqwry.dat');
				$addressName = $ipLocation->getAddrName($address);
				$cityList = explode(',', $wechatData['city']);
				foreach ( $cityList as $value ) {
					if( stripos($addressName, $value) !== false ) {
						Db::table('cfg_service_internal')->where('wechat', $wechatData['wechat'])->inc('number')->update(['lasttime' => date('Y-m-d H:i:s')]);
						$wechatArray = ['wechat'=> $wechatData['wechat'], 'sex'=> $wechatData['sex'], 'name'=> $wechatData['nickname'], 'phone'=> $wechatData['phone'], 'qrcode' => $wechatData['qrcode'], 'company' => $siteQuery['Copyright']];
						break;
					}
				}
			}
		}

        // 写入访问记录
        Db::name('cfg_access')->insert(['companyId' => $companyId, 'userid' => $expandQuery['userid'], 'customerid' => $expandQuery['customerid'], 'contact' => $expandQuery['contact'], 'username' => $expandQuery['username'], 'userType' => $expandQuery['userType'], 'dpi' => $width.'x'.$height,
        	'bazaarId' => $siteQuery['bazaar'], 'domain' => $domainUrl, 'word' => $word, 'url' => $href, 'staySecond' => $timer, 'ip' => $address, 'accessPage' => $pages, 'offset' => $offset,
        	'keywordId' => $e_keywordid, 'browser' => $device,'device'=>$dev, 'md5' => $accesMd5, 'accessTime' => date('Y-m-d H:i:s'), 'service' => serialize($wechatArray)]);

        // 更新微信最后展示时间
        if( $numberCount == 0) {
        	Db::table('cfg_service')->where('companyId', $companyId)->where('wechat', $wechatData['wechat'])->inc('number')->update(['lasttime' => date('Y-m-d H:i:s')]);
        }

		return json(['code'=>0, 'data'=> $wechatArray, 'sign' => $accesMd5]);
	}

	/**
	 * 记录复制记录
	 * 纠正时间2021-11-11 12-20
	 * 最后纠正时间2022-10-26 11-20
	 * return json
	 */
	public function setData(Request $request)
	{
		$address = $this->GetIP();
		if( $this->qps_firewall('set_'.$address, 100) ) {
			return json(['code'=>8888, 'data'=> []]);
		}

		$t = $request->param('t', '', 'trim');
		$vid = $request->param('vid', '', 'trim');
		$header = $request->header('user-agent');
		$pages = $request->param('pages', '', 'trim');
		$width = $request->param('width', '', 'trim');
		$height = $request->param('height', '', 'trim');
		$language = $request->param('language', '', 'trim');
		$platform = $request->param('platform', '', 'trim');
		$device = $request->param('device', '', 'trim');
			$dev = $request->param('dev', '', 'trim');
		$code = $request->param('code', '', 'trim');
		$href = $request->param('href', '', 'trim');
		$word = $request->param('word', '', 'trim');
		$timer = $request->param('timer', '', 'trim');
		$index = $request->param('index', '', 'trim');
		$offset = $request->param('offset', '', 'trim');
		$wechat = $request->param('wechat', '', 'trim');
		$content = $request->param('content', '', 'trim');
		$referrer = $request->param('referrer', '', 'trim');
		$userAgent = $request->param('userAgent', '', 'trim');
		$companyId = $request->param('companyId', '', 'trim');
		$colordepth = $request->param('colordepth', '', 'trim');
		$e_keywordid = $request->param('e_keywordid', '', 'trim');
		if( empty($href) ) {
			return json(['code'=>1000, 'data'=> []]);
		}

		if( empty($header) ) {
			return json(['code'=>1000, 'data'=> []]);
		}

		if( empty($companyId) ) {
			return json(['code'=>1000, 'data'=> []]);
		}

		// 获取URL域名
		$domainUrl = cloud_domain_format($href);
		if( empty($domainUrl) ) {
			return json(['code'=>1000, 'data'=> []]);
		}

		// URL解码
		if($href) {
			$href = urldecode($href);
		}

		if($word) {
			$word = urldecode($word);
		} else {
			$word = null;
		}

		if($content) {
			$content = urldecode($content);
		}

		if($referrer) {
			$referrer = urldecode($referrer);
		}

		// 拦截蜘蛛访问
		$userAgent = strtolower($userAgent);
		foreach( ['bot', 'crawl', 'spider' ,'slurp', 'sohu-search', 'lycos', 'robozilla'] as $value ) {
			if( strpos($userAgent, $value) !== false ) {
				return json(['code'=>2000, 'data'=> []]);
			}
		}

		// 拦截访问IP
		$interceptPath = app()->getRootPath() . 'data' . DIRECTORY_SEPARATOR . md5($companyId . 'spider' );
		if ( file_exists($interceptPath) ) {
			$interceptData = file_get_contents($interceptPath);
			if( $interceptData ) {
				$getAddress = explode(".", $address);
				if( strpos($interceptData, "{$getAddress[0]}.{$getAddress[1]}.{$getAddress[2]}") !== false ) {
					return json(['code'=>2000, 'data'=> []]);
				}
			}
		}

    // 查询微信是否存在
		$wechatQuery = Db::table('cfg_service')->field('id, name, nickname, wechat')->where('companyId', $companyId)->where('wechat', $wechat)->find();
		if(!isset($wechatQuery['id'])) {
			return json(['code'=>3000, 'data'=> []]);
		}
	
		// 查询落地页
		$siteQuery = Db::table('cfg_site')->field('id, bazaar')->where('companyId', $companyId)->where('DomainUrl', $domainUrl)->where('status', 1)->find();
		if( !is_array($siteQuery) ) {
			return json(['code'=>4000, 'data'=> []]);
		}
		if( !isset($siteQuery['id']) ) {
			return json(['code'=>4000, 'data'=> []]);
		}
		if( empty($siteQuery['id']) ) {
			return json(['code'=>4000, 'data'=> []]);
		}

		// 查询推广平台
		$expandQuery = Db::table('cfg_expand')->field('id, userid, customerid, contact, username, userType, ocpcType, ocpcCode')->where('bazaarId', $siteQuery['bazaar'])->whereFindInSet('domainIds', $siteQuery['id'])->find();
		if( !is_array($expandQuery) ) {
			return json(['code'=>5000, 'data'=> []]);
		}
		if( !isset($expandQuery['id']) ) {
			return json(['code'=>5000, 'data'=> []]);
		}
		if( empty($expandQuery['id']) ) {
			return json(['code'=>5000, 'data'=> []]);
		}

		// 记录复制记录
		if(empty($e_keywordid)) {
			$e_keywordid = null;
		}

		// 百度VID
		if(empty($vid)) {
			$vid = null;
		}
 
		$accesMd5 = md5(date('Ymd') . $companyId . $pages . $device . $language . $platform . $href . $e_keywordid . $colordepth . $word . $referrer . $address . $wechat);
		$copyQuery = Db::table('cfg_copy')->where('companyId', $companyId)->where('md5', $accesMd5)->value('id');
		if( empty($copyQuery) ) {
			Db::name('cfg_copy')->insert(['companyId' => $companyId, 'vid' => $vid, 'userid' => $expandQuery['userid'], 'customerid' => $expandQuery['customerid'], 'contact' => $expandQuery['contact'], 'username' => $expandQuery['username'], 'userType' => $expandQuery['userType'], 'bazaarId' => $siteQuery['bazaar'],
			  'ocpcCode' => $expandQuery['ocpcCode'], 'domain' => $domainUrl, 'url' => $href, 'accessPage' => $pages, 'staySecond' => $timer, 'copySeconds' => $timer, 'level' => $index, 'content' => $content, 'wechat' => $wechat, 'ip' => $address, 
				'wechatName' => $wechatQuery['name'], 'wechatNickname' => $wechatQuery['nickname'], 'dpi' => $width.'x'.$height, 'browser' => $device,'device'=>$dev, 'copyTime' =>  date("Y-m-d H:i:s"), 
				'ocpcType' => $expandQuery['ocpcType'], 'ocpcStatus' => 1, 'md5' => $accesMd5, 'word' => $word, 'keywordId' => $e_keywordid
			]);
			return json(['code'=>200, 'data'=> []]);
		}

    // 更新停留时长
		Db::name('cfg_copy')->where('id', $copyQuery)->update(['staySecond' => $timer, 'content' => $content]);
		return json(['code'=>200, 'data'=> []]);

	}

	/**
	 * 查询微信接口
	 * 最后纠正时间2021-11-11 12-20
	 * return json
	 */
	public function setOnline(Request $request)
	{
		$address = $this->GetIP();
		if( $this->qps_firewall('online_'.$address, 360) ) {
			return json(['code'=>8888, 'data'=> []]);
		}

		$t = $request->param('t', '', 'trim');
		$vid = $request->param('vid', '', 'trim');
		$header = $request->header('user-agent');
		$pages = $request->param('pages', '', 'trim');
		$width = $request->param('width', '', 'trim');
		$height = $request->param('height', '', 'trim');
		$language = $request->param('language', '', 'trim');
		$platform = $request->param('platform', '', 'trim');
		$device = $request->param('device', '', 'trim');
		$code = $request->param('code', '', 'trim');
		$href = $request->param('href', '', 'trim');
		$word = $request->param('word', '', 'trim');
		$timer = $request->param('timer', '', 'trim');
		$offset = $request->param('offset', '', 'trim');
		$referrer = $request->param('referrer', '', 'trim');
		$userAgent = $request->param('userAgent', '', 'trim');
		$companyId = $request->param('companyId', '', 'trim');
		$colordepth = $request->param('colordepth', '', 'trim');
		$e_keywordid = $request->param('e_keywordid', '', 'trim');

		if( empty($href) ) {
			return json(['code'=>1000, 'data'=> []]);
		}

		if( empty($header) ) {
			return json(['code'=>1000, 'data'=> []]);
		}

		if( empty($companyId) ) {
			return json(['code'=>1000, 'data'=> []]);
		}

		// 获取URL域名
		$domainUrl = cloud_domain_format($href);
		if( empty($domainUrl) ) {
			return json(['code'=>1000, 'data'=> []]);
		}

		// URL解码
		if($href) {
			$href = urldecode($href);
		}
		
		if($word) {
			$word = urldecode($word);
		} else {
			$word = null;
		}
		
		if($referrer) {
			$referrer = urldecode($referrer);
		}

		// 拦截蜘蛛访问
		$userAgent = strtolower($userAgent);
		foreach( ['bot', 'crawl', 'spider' ,'slurp', 'sohu-search', 'lycos', 'robozilla'] as $value ) {
			if( strpos($userAgent, $value) !== false ) {
				return json(['code'=>2000, 'data'=> []]);
			}
		}

		// 拦截访问IP
		$interceptPath = app()->getRootPath() . 'data' . DIRECTORY_SEPARATOR . md5($companyId . 'spider' );
		if ( file_exists($interceptPath) ) {
			$interceptData = file_get_contents($interceptPath);
			if( $interceptData ) {
				$getAddress = explode(".", $address);
				if( strpos($interceptData, "{$getAddress[0]}.{$getAddress[1]}.{$getAddress[2]}") !== false ) {
					return json(['code'=>2000, 'data'=> []]);
				}
			}
		}

       // 数据安全码
		$query = Db::table('cfg_access')->field('id, offset')->where('companyId', $companyId)->where('word', $word)->where('md5', $code)->find();
		if($query){
			$offsetArray = explode('|', $query['offset']);
			if(!in_array($offset, $offsetArray)) {
				array_push($offsetArray, $offset);
			}
			Db::name('cfg_access')->where('id', $query['id'])->update(['staySecond' => $timer, 'offset' => implode('|', $offsetArray)]);
			return response(null, 200, ['Content-Type' => 'image/png']);
		}

		// 查询落地页
		$siteQuery = Db::table('cfg_site')->field('id, bazaar, SiteModel, Copyright')->where('companyId', $companyId)
		  ->where('DomainUrl', $domainUrl)->where('status', 1)->find();
		if( !is_array($siteQuery) ) {
			return response(null, 200, ['Content-Type' => 'image/png']);
		}

		if( !isset($siteQuery['id']) ) {
			return response(null, 200, ['Content-Type' => 'image/png']);
		}

		if( empty($siteQuery['id']) ) {
			return response(null, 200, ['Content-Type' => 'image/png']);
		}

		// 查询当前推广平台
		$expandQuery = Db::table('cfg_expand')->field('id, userid, customerid, contact, username, userType')->where('bazaarId', $siteQuery['bazaar'])->whereFindInSet('domainIds', $siteQuery['id'])->find();
		if( !is_array($expandQuery) ) {
			return response(null, 200, ['Content-Type' => 'image/png']);
		}
		if( !isset($expandQuery['id']) ) {
			return response(null, 200, ['Content-Type' => 'image/png']);
		}
		if( empty($expandQuery['id']) ) {
			return response(null, 200, ['Content-Type' => 'image/png']);
		}

	//	$service = Db::table('cfg_access')->where('companyId', $companyId)->field('id, offset')->where('md5', $code)->value('service');
	//	if($service) {
	//		$accesMd5 = md5(date('Ymd') . $companyId . $domainUrl . $userAgent . $address);
	//		Db::name('cfg_access')->insert(['companyId' => $companyId, 'userid' => $expandQuery['userid'], 'customerid' => $expandQuery['customerid'],  'contact' => $expandQuery['contact'], 'username' => $expandQuery['username'], 'userType' => $expandQuery['userType'], 'dpi' => $width.'x'.$height,
	//			'bazaarId' => $siteQuery['bazaar'], 'domain' => $domainUrl, 'word' => $word, 'url' => $href, 'staySecond' => $timer, 'ip' => $address, 'accessPage' => $pages, 'offset' => $offset,
	//			'keywordId' => $e_keywordid, 'browser' => $device, 'md5' => $accesMd5, 'accessTime' => date('Y-m-d H:i:s'), 'service' => $service]);
	//	}

		return response(null, 200, ['Content-Type' => 'image/png']);

	}

}